package BanyuanClub.Study.Day0310.网络编程;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

public class Server {
    public static void main(String[] args) {
        try {
            //创建一个服务端并添加端口号
            ServerSocket server = new ServerSocket(8888);
            //控制台输入
            Scanner in = new Scanner(System.in);
            System.out.println("服务端已启动");
            //线程安全的HashMap
            ConcurrentHashMap<String ,PrintWriter> outs = new ConcurrentHashMap<>();

            //负责群发
            new Thread(()->{
                while (true){
                    String st = in.next();
                    for (PrintWriter out : outs.values()
                         ) {
                        out.println("服务器：" + st);
                    }
                }
            }).start();

            int index = 1;
            while (true){
                Socket socket = server.accept();
                System.out.println("已链接");
                PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
                BufferedReader bis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                outs.put(index++ + "" ,pw);

                //负责客户端
                new Thread(()->{
                    while (true) {
                        try {
                            String s = bis.readLine();
                            String[] arr = s.split("#");
                            //群发
                            if ("all".equals(arr[0])){
                                for (PrintWriter out1 : outs.values()
                                ) {
                                    out1.println(arr[1]);
                                }
                            }
                            //私发
                            else {
                                outs.get(arr[0]).println(arr[1]);
                            }
                            System.out.println(s);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
